import { Injectable, OnDestroy } from '@angular/core';
import { URLSearchParams, Http, Headers, RequestOptionsArgs, RequestOptions } from '@angular/http';
import { environment } from '../../../environments/environment';

//Models
import { AuthModel } from '../../models/auth.model';
//Services
import { GAService } from '../services/ga.service';

@Injectable()
export class BaseHttpService implements OnDestroy {    
    //url for _UI back-end service (may have different domain than front-end)
    public readonly serverUrl: string =  environment.serviceUrl;    
  
    public gaService: GAService;    

    constructor(private baseHttp: Http) { 
        this.gaService = new GAService();
    }
 
    ngOnDestroy() {
        //BaseHttpService.gaService.disconnect();
    } 

    public get<T>(url: string, options?: RequestOptionsArgs): Promise<T> {
        let promise = new Promise<T>((resolve, reject) => {
            this.gaService.connect().then((authObj)=>{
                this.baseHttp.get(url, this.addAuthHeader(authObj, options)).subscribe(
                    data => resolve(data.json()),
                    msg => reject(msg)
                );                        
            })
            .catch((msg) => reject(msg));
        });

        return promise;
    }  

    public post<T>(url: string, body: any, options?: RequestOptionsArgs): Promise<T> {
        let promise = new Promise<T>((resolve, reject) => {
            this.gaService.connect().then((authObj)=>{
                this.baseHttp.post(url, body, this.addAuthHeader(authObj, options)).subscribe(
                    data => resolve(data.json()),
                    msg => reject(msg)
                );                        
            })
            .catch((msg) => reject(msg));
        });

        return promise;
    } 

    public urlEncodeObject(object: any): URLSearchParams {        
        var ret = new URLSearchParams();
        for(var field in object)
        {
            if (object[field] instanceof Array)
            {
                for(var i = 0; i < object[field].length; i++)
                {
                   ret.append(field, object[field][i]);
                }
            }
            else{
                ret.set(field, object[field]);
            }
        }
            
        return ret;
    }

    private addAuthHeader(authObj: AuthModel, options?: RequestOptionsArgs): RequestOptionsArgs {
        if (options == null) {
            options = new RequestOptions();
        }
        if (options.headers == null) {
            options.headers = new Headers();
        }
        options.headers.append('Authorization', `Bearer ${authObj.token}`);

        return options;
    }

}